package ch12;

class ThreadEx16 {
	public static void main(String args[]) {
		Runnable r = new RunnableEx16();
		Thread t1 = new Thread(r);
		Thread t2 = new Thread(r);

		t1.start();
		t2.start();
	}
}

class Account16 {
	int balance = 1000;

	public synchronized void withdraw(int money){	
		while(balance < money){
			try{ wait(); } catch(InterruptedException e) {}
		}
		balance -= money;
	}
	
	public synchronized void deposit(int money){
		balance += money;
		notifyAll();
	}
}

class RunnableEx16 implements Runnable {
	Account16 account = new Account16();

	public void run() {
		while(account.balance > 0) {			
			int money = (int)(Math.random() * 3 + 1) * 100;
			account.withdraw(money);
			System.out.println("balance:"+account.balance);
		}
	}
}
/*
balance:700
balance:400
balance:100
*/